package com.wzp;

/**
 * 反转链表
 *
 * @author zhengpeng.wang
 */
public class ReverseLinkedList {

    static class ListNode {
        int val;
        ListNode next;

        public ListNode(int val, ListNode next) {
            this.val = val;
            this.next = next;
        }
    }

    public static ListNode iterate(ListNode head) {
        ListNode pre = null, next;
        ListNode curr = head;
        while (curr.next != null) {
            next = curr.next;
            curr.next = pre;
            pre = curr;
            curr = next;
        }
        return pre;
    }

    /**
     * 解法2：递归：以相似的方法重复，类似于树结构，先从根节点找到叶子节点，从叶子节点开始遍历
     * 大的问题(整个链表反转)拆成性质相同的小问题(两个元素反转)curr.next.next = curr 将所有的小问题解决，大问题即解决
     * <p>
     * 只需每个元素都执行curr.next.next = curr，curr.next = null两个步骤即可 为了保证链不断，必须从最后一个元素开始
     */
    public static ListNode recursion(ListNode curr) {
        if(curr == null || curr.next == null){
            return curr;
        }
        ListNode newHead = recursion(curr.next);
        curr.next.next = curr;
        curr.next = null;
        return newHead;
    }

    public static void main(String[] args) {
        ListNode node5 = new ListNode(5, null);
        ListNode node4 = new ListNode(4, node5);
        ListNode node3 = new ListNode(3, node4);
        ListNode node2 = new ListNode(2, node3);
        ListNode node1 = new ListNode(1, node2);
//        ListNode node_1 = iterate(node1);
        ListNode node_1 = recursion(node1);
        System.out.println(node_1);
    }
}
